﻿package com.gobang.netmode.serverdata.LAN;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Stack;

import com.gobang.gobangui.MainWindowUI;
import com.gobang.netmode.sendandreceive.Message;
import com.gobang.netmode.sendandreceive.MessageMSG;
import com.gobang.netmode.sendandreceive.Order;
import com.gobang.netmode.sendandreceive.SendAndReceive;
import com.gobang.netmode.util.ClientDataClass;
import com.gobang.netmode.util.ServerMessage;



// 声明服务端线程：循环接收客户端信息，完成信息的翻译，并根据信息反馈给所有的客户
public class ServerForRoomClientOfLAN extends Thread {
	ServerOfLAN server = null;
	public SendAndReceive sendAndReceive ;
	ClientDataClass client = null;
	Message message = new Message();
	boolean isRun=true;
	Stack<MessageLog> receiveMessageStack=new Stack<MessageLog>();
	Stack<MessageLog> sendMessageStack=new Stack<MessageLog>();
	
	public ServerForRoomClientOfLAN(Socket clientSocket, ServerOfLAN server) throws FileNotFoundException { // 构造方法
		// 每构造一个线程，说明就有一个客户端连上，立即向客户端发送链接成功及房间信息
		sendAndReceive = new SendAndReceive(clientSocket);
		this.server =server;
		if(MainWindowUI.isDebug()){
		String filePath = System.getProperty("java.io.tmpdir") + "gobangtemp\\Netdebug";
	    File file=new File(filePath);  
	  //如果文件夹不存在则创建  
	  if  (!file .exists()){     
	      file .mkdirs();  
	  } 
		String filenameOut = filePath+"\\ServerOut"+this+".txt";
		String filenameErr = filePath +"\\ServerErr"+this+".txt";
		PrintStream outPrintStream=new PrintStream(filenameOut);
		PrintStream errStream =new PrintStream(filenameErr);
		System.setOut(outPrintStream);
		System.setErr(errStream);
		}
		
	}

	public void run() {
		try {
			while (server.getIsWork()&& isRun) {
					message = sendAndReceive.receiveMessage();
					receiveMessageStack.push(new MessageLog(message));
					System.out.println("ServerThread.run()收到客户端消息："+message);
					if (message != null) {//能收到消息
						if(client == null){
							client = message.clientDataClass;
							System.out.println("ServerForRoomClient.run()"+server.clientdataVec.size());
						}
						if (message.order != Order.NULL) {// 从解析出来的信息中含有命令操作，则执行相应的操作
							server.clientOperationOfLAN.operation(this, message);// 对命令进行操作，还要知道对象是this这个线程
						}
					} else {
						System.out.println("ServerThread:该用户下线或无法收到消息" + client);
						isRun=false;
						sendAndReceive.close();
						if(client != null){
						server.remove(this);// 删除该线程的信息
						}
					}
			}//while (server.getIsWork()&& isRun) end
		} catch (ClassNotFoundException e) {
			System.out.println(this + "ServerThread: 无法收到客户端信息,ClassNotFoundException" + client);
			e.printStackTrace();
		}
	}// run() end
@Override
public boolean equals(Object obj) {
	if(obj == null || this.client == null){
		return false;
	}
	if(((ServerForRoomClientOfLAN)obj).client != null){
		if(((ServerForRoomClientOfLAN)obj).client.equals(this.client)){
			return true;
		}else{
			return false;
		}
	}else{
		return  false;
	}
}
	public void connectSuccess() {// 连接成功，反馈回房间的信息
		Message message = new Message();
		message = getRoomMessage();
		sendAndReceive.sendMessage(message);
	}

	
	public  synchronized boolean sendAClient(Message message) {
		// 向自己发送数据流
			if (sendAndReceive.sendMessage(message))// 打包好发给用户的数据
			{
				sendMessageStack.push(new MessageLog(message));
				return true;
			} else {
				return false;
			}
	}
	public  synchronized boolean sendAClient(ServerForRoomClientOfLAN s, Message message) {
		// 向该用户发送数据流
			if (s.sendAndReceive.sendMessage(message))// 打包好发给用户的数据
			{
				s.sendMessageStack.push(new MessageLog(message));
				return true;
			} else {
				return false;
			}
	}

	public synchronized int sendClients(Message message) {// 向每一位客户发送数据流
		// 向该用户发送数据流,返回发送成功的用户人数
		int count = 0;
		int index;
		ServerForRoomClientOfLAN s;
		for (index = 0; index < server.clients.size(); index++) {
			s = server.clients.get(index);
			if (s.sendAndReceive.sendMessage(message)) // 打包好发给用户的数据
			{
				s.sendMessageStack.push(new MessageLog(message));
				count++;
			} else {
				server.clients.remove(index);
			}
		}
		return count;
	}

	public synchronized int sendClientExceptOwn(Message message) {
		// 向该用户发送数据流,返回发送成功的用户人数
		int count = 0;
		ServerForRoomClientOfLAN s;
		for (int index = 0; index < server.getServerThread().size(); index++) {
			s = server.getServerThread().get(index);
			if (!s.equals(this)) {
				if (s.sendAndReceive.sendMessage(message)) // 打包好发给用户的数据
				{
					s.sendMessageStack.push(new MessageLog(message));
					count++;
				} else {
					server.remove(s);// 尽快删除该线程
					System.out.println("ServerThread.sendClientExceptOwn()失败，该线程已被删除！" + s.client);
				}
			}
		}
		return count;
	}
	public Message getRoomMessage() {//针对局域网而言，只获取一个房间的信息
		Message message = new Message();
		ServerMessage serverMessage = server.getServerMessage();
		serverMessage.setRoomNum(server.clientdataVec.size());
		message.msg = MessageMSG.ORDER + MessageMSG.SERVER_MESSAGE;
		message.order = Order.ROOMMSG;
		message.serverMessage = serverMessage;
		return message;
	}
}